package com.kitbox.hl.meshow.common.utils;


import cn.hutool.log.dialect.log4j.Log4jLog;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import javax.xml.transform.ErrorListener;
import java.io.File;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RuiUtils {
	private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(RuiUtils.class);
	public final static String CHANGE_LINE_ALPH = "\n";
	
	public final static String PUB_SPLIT_ALPH = ",";
	
	public final static String CONFLICT_REPLACE_ALPH = "|";
	
	public static String CONTEXT_PATH = "";// 应用路径

	/**
	 * 判断字符串是否为null 或者 trim后为"";
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isTrimEmpty(String str) {
		if (str == null || "".equals(str.trim())) {
			return true;
		}
		return false;
	}

	public static String getNoNullString(String str) {
		if (str == null) {
			return "";
		}
		return str.trim();
	}

	/**
	 * 判断字符串是否 不 为null 而且 trim后 不 等于"";
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNotTrimEmpty(String str) {
		return !isTrimEmpty(str);
	}

	/**
	 * 数据库中读取的Object类型，如果不为null,转换成Double型并返回
	 * 
	 * @param object
	 * @return
	 */
	public static Double getDoubleValue(Object object) {
		if (object == null) {
			return 0.0;
		} else {
			if (StringUtils.isEmpty(object.toString())) {
				return 0.0;
			}
			return Double.valueOf(object.toString());
		}
	}

	/**
	 * 判断对象数组是否为空
	 *
	 * @param //objs 需要判断的对象数组
	 * @return boolean
	 */
	public static boolean isWindows() {
		String osName = System.getProperty("os.name");
        if (osName == null)
        {
        	osName = "";
        }
        else
        {
        	osName = osName.toUpperCase();
        }
        if (osName.contains("WINDOWS"))
        {
        	return true;
        }
        return false;
	}
	
	

	public static String getArrayProperty(String[] strArray, int i) {
		if (strArray.length > i) {
			return strArray[i];
		}
		return null;
	}

	/**
	 * 
	 * @param string
	 *            传入的字符
	 * @param filler
	 *            用来填充的数字
	 * @param totalLength
	 *            总的字符长度
	 * @param atEnd
	 *            数字房子头部或者结尾
	 * @return
	 */
	public static String fillString(String string, char filler,
			int totalLength, boolean atEnd) {
		byte[] tempbyte = string.getBytes();
		int currentLength = tempbyte.length;
		int delta = totalLength - currentLength;
		for (int i = 0; i < delta; i++) {
			/**
			 * 将数字放在头部
			 */
			if (atEnd) {
				string += filler;
			} else {
				/**
				 * 将数字放在结尾
				 */
				string = filler + string;
			}
		}
		return string;
	}

	public static String getSimpleDateStr(String dateStr) {
		if (isNotTrimEmpty(dateStr) && dateStr.length() == 10) {
			return dateStr.substring(5).replaceAll("-", "/");
		}
		return "";
	}

	public static String getLength18IdNo(String id) {
		if (id == null) {
			id = "";
		}
		id = id.trim();
		if (id.length() != 15) {
			return id;
		}
		final int[] W = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2,
				1 };
		final String[] A = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3",
				"2" };
		int i, j, s = 0;
		String newid;
		newid = id;
		newid = newid.substring(0, 6) + "19" + newid.substring(6, id.length());
		for (i = 0; i < newid.length(); i++) {
			j = Integer.parseInt(newid.substring(i, i + 1)) * W[i];
			s = s + j;
		}
		s = s % 11;
		newid = newid + A[s];
		return newid;
	}

	public static String getSystemEncoding() {
		return System.getProperty("file.encoding");
	}

	public static String getMaxLengthStr(String string, int length) {
		if (string == null)
		{
			return "";
		}
		else if (string.length() > length)
		{	
			return string.substring(0, length);
		}
		else
		{
			return string;
		}
	}
	
	/**
	 * 根据自定义短信格式返回要发送的短消息内容
	 * 
	 * @param s
	 * @param convertMap
	 * @return
	 */
	public static String getMessage(String s, Map<String, String> convertMap)
	{
		String custMessage = s;

		if (custMessage != null)
		{
			String regEx = "\\$\\{[a-zA-Z]*\\}";
			Pattern p = Pattern.compile(regEx);
			Matcher m = p.matcher(custMessage);
			String replaceValue;
			while (m.find())
			{
				String replaceStr = m.group();
				String key = replaceStr.substring(2, replaceStr.length() - 1);
				replaceValue = convertMap.get(key);
				if (replaceValue == null)
				{
					replaceValue = "";
				}
				custMessage = custMessage.replace(replaceStr, replaceValue);
			}

		}
		return custMessage;
	}

	public static Map<String, String> strArr2Map(List<Object[]> jdbcList) {
		Map<String, String> result = new HashMap<String, String>();
		for (Object[] values : jdbcList)
		{
			result.put(String.valueOf(values[0]), String.valueOf(values[1]));
		}
		return result;
	}

	public static String getStrInCondition(List<String> ids, String name) {
		StringBuffer inCondition = new StringBuffer("(" + name + " in (");
		int flag = 0;
		for (Object id : ids) {
			if (flag == 999) {
				inCondition = new StringBuffer(inCondition.substring(0,
						inCondition.length() - 1));
				inCondition.append(") or " + name + " in (");
				flag = 0;
			}
			inCondition.append("'").append(id).append("',");
			flag++;
		}
		String str = inCondition.toString();
		//oracle问题，in语句 如果是一个内容效率非常滴，如果in里面有2个内容就快很多。
		if (str.endsWith(",")) {
			str += "'-_!@*($@XASD'";
		} else {
			str += "'-_$%$#SKDUJ5', '-_!@*($@XASD'";
		}
		str += ") ) ";
		return str;
	}
	
	/**
	 * 适合锐开的entity复制，只支持util.Date, String, Long, Double复制
	 * @param orig
	 * @param desc
	 * @throws Exception 
	 */
	public static void copyProperties(Object orig, Object desc) throws Exception {
		if (orig == null || desc == null)
		{
			throw new Exception("源对象和目标对象都不能为空");
		}
		for (Method method : orig.getClass().getMethods())
		{
			int length = method.getParameterTypes().length;
			if (method.getName().contains("get") && length == 0 && method.getReturnType() != null && acceptedType(method.getReturnType()))
			{
				Object value = method.invoke(orig);
				String fieldName = method.getName().substring(3);
				if (isNotTrimEmpty(fieldName))
				{
					fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
					try
					{
						BeanUtils.setProperty(desc, fieldName, value);
					}
					catch(Exception e)
					{

						logger.error("属性" + fieldName + "复制失败");
					}
				}
			}
		}
	}
	
	/**
	 * 是否是锐开entity可识别的数据类型
	 * @param returnType
	 * @return
	 */
	private static boolean acceptedType(Class<?> returnType) {
		if (returnType != null)
		{
			for (String type : ACCEPTED_TYPE_LIST)
			{
				if (returnType.toString().contains(type))
				{
					return true;
				}
			}
		}
		return false;
	}

	

	

	
	private static List<String> ACCEPTED_TYPE_LIST = new ArrayList<String>();
	
	static {
		ACCEPTED_TYPE_LIST.add("String");
		ACCEPTED_TYPE_LIST.add("Long");
		ACCEPTED_TYPE_LIST.add("Double");
		ACCEPTED_TYPE_LIST.add("Date");
	}
	

	public static String getPureHtmlStr(String str)
	{
		if (str == null)
		{
			return "";
		}
		return str.replace("<", "&lt;").replace(">", "&gt;").replace("\n", "</br>").replace("　", "&nbsp;").replace(" ", "&nbsp;");
	}
	
	/**
	 * 把卡系统的分字符串变成元为单位的字符
	 * @param fen
	 * @return
	 */
	public static String fen2Yuan(String fen)
	{
		while (fen.startsWith("0"))
		{
			fen = fen.substring(1);
		}
		return fen.substring(0, fen.length() - 2) + "." + fen.substring(fen.length() - 2);
	}
	
	
	public static String formatDouble(Double d, String format)
	{
		if (format == null || "".equals(format.trim()))
		{
			format = "0.00";
		}
		DecimalFormat f = new DecimalFormat(format);
		if(d >0){
			d = d + 0.00000000000001d;
		}else if(d < 0){
			d = d - 0.00000000000001d;
		}
		return f.format(d);
	}
	
	public static String formatDouble(Double d)
	{
		return formatDouble(d, null);
	}
	
	public static String[] getBirthAndGender(String zjNo) throws Exception{
		String[] identityAry = new String[]{"",""};
		if (RuiUtils.isNotTrimEmpty(zjNo) && zjNo.toUpperCase().matches("[0-9]{15}|[0-9]{17}([0-9]|X)")){
			//15位身份证
			if (zjNo.length() == 15){
				String birth = zjNo.substring(6,12);
				String gender = Integer.parseInt(zjNo.substring(14))%2 == 0?"女":"男";
				identityAry[0] = "19" + birth;
				identityAry[1] = gender;
			} else if (zjNo.length() == 18){
			//18位身份证
				String birth = zjNo.substring(6,14);
				String gender = Integer.parseInt(zjNo.substring(16,17))%2==0?"女":"男";
				identityAry[0] = birth;
				identityAry[1] = gender;
			}
		}
		return identityAry;
	}

	
	
	/**
	 * 获取6位随机数
	 * @return
	 */
	public static String getTransSeq() {
		String seq = String.valueOf(Math.random());
		seq = seq.substring(seq.indexOf('.') + 1);
		if (seq.length() < 6)
		{
			seq = RuiUtils.fillString(seq, '0', 6, false);
		}
		else if (seq.length() > 6)
		{
			seq = seq.substring(0, 6);
		}
		return seq;
	}
	
	/**
	 * 将短信模板变成最终短信内容
	 * @param smsFinal
	 * @param valuesMap
	 * @return
	 */
	public static String decorateSms(String smsFinal,
			Map<String, String> valuesMap) {
		String result = smsFinal;
		for (String key : valuesMap.keySet())
		{
			result = result.replace(key, valuesMap.get(key));
		}
		return result;
	}

	public static byte[] subByte(byte[] bytes, int index, int length) {
		byte[] result = new byte[length];
		for (int j = 0; j < length; j++) {
			result[j] = bytes[index + j];
		}
		return result;
	}
	
	public static String getArrayValue(String[] arr, int i) throws Exception{
		if(arr.length > i){
			return arr[i] == null ? "" : arr[i].toString();
		}else{
			return "";
		}
	}

	public static String getTempFilePath() {
		String tempFilePath = "/app/tmnew/tmtemp/export/";
		if (RuiUtils.isWindows()) {
			tempFilePath = "C:/data/tmnew/tmtemp/export/";
		}
		File dir = new File(tempFilePath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return tempFilePath;
	}
	
	/**
	 * 获取服务器节点名称
	 * Node命名规范 MAIN_NODE, A_NODE1,  B_NODE2
	 * @return
	 */
	public static String getNodeName()
	{
		String nodeName = System.getProperty("NODE_NAME");
		logger.info("NODE_NAME = " + nodeName);
		return nodeName == null ? "" : nodeName;
	}
	
	/**
	 * 判断是否是负载均衡服务器的主节点
	 * @return
	 */
	public static boolean isMainNode()
	{
		if(RuiUtils.isWindows()){
			/**测试环境中直接返回TRUE*/
			return true;
		}
		String nodeName = getNodeName();
		return "MAIN_NODE".equals(nodeName);
	}
	
}
